<template>
  <div class="init-container">
    <div class="mask-container" v-if="isMask"></div>
    <div class="container">
      <!-- PH添加表格 -->
      <div class="quadrant-title">风机PH添加</div>
      <vxe-table
        class="table"
        :data="phTanks"
        border
        show-overflow
        :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }"
      >
        <vxe-column type="seq" width="60"></vxe-column>
        <vxe-column field="name" title="参数名称"></vxe-column>
        <vxe-column
          field="upAlarmLimit.value"
          title="报警上限"
          :edit-render="{}"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.upAlarmLimit.value"
              type="number"
              :min="0"
              :max="14"
              :step="0.001"
              @blur="handleBlur(row, 'upAlarmLimit', 'phTanks')"
            />
          </template>
        </vxe-column>
        <vxe-column
          field="setUpperLimit.value"
          title="设定上限"
          :edit-render="{}"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.setUpperLimit.value"
              type="number"
              :min="0"
              :max="14"
              :step="0.001"
              @blur="handleBlur(row, 'setUpperLimit', 'phTanks')"
            />
          </template>
        </vxe-column>
        <vxe-column
          field="setLowerLimit.value"
          title="设定下限"
          :edit-render="{}"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.setLowerLimit.value"
              type="number"
              :min="0"
              :max="14"
              :step="0.001"
              @blur="handleBlur(row, 'setLowerLimit', 'phTanks')"
            />
          </template>
        </vxe-column>
        <vxe-column
          field="lowAlarmLimit.value"
          title="报警下限"
          :edit-render="{}"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.lowAlarmLimit.value"
              type="number"
              :min="0"
              :max="14"
              :step="0.001"
              @blur="handleBlur(row, 'lowAlarmLimit', 'phTanks')"
            />
          </template>
        </vxe-column>
        <vxe-column field="actualValue.value" title="实际PH值"></vxe-column>
        <vxe-column field="autoSwitch.value" title="自动开关">
          <template #default="{ row }">
            <i-switch
              size="large"
              v-model="row.autoSwitch.value"
              @on-change="
                handleSwitchChange(
                  row,
                  'autoSwitch',
                  'phTanks',
                  row.autoSwitch.value
                )
              "
            >
              <span slot="open">自动</span>
              <span slot="close">手动</span>
            </i-switch>
          </template>
        </vxe-column>
        <vxe-column field="waterStatus.value" title="补水状态">
          <template #default="{ row }">
            <Button
              :disabled="row.autoSwitch.value"
              class="ivu-btn"
              :type="row.waterStatus.value ? 'success' : 'error'"
              @click="
                handleSwitchChange(
                  row,
                  'waterStatus',
                  'phTanks',
                  row.waterStatus.value
                )
              "
            >
              {{ row.waterStatus.value ? '开启中' : '已停止' }}
            </Button>
          </template>
        </vxe-column>
        <vxe-column field="alarmStatus.value" title="报警状态">
          <template #default="{ row }">
            <Tag
              v-if="row.alarmStatus.value"
              class="alarm-status"
              color="error"
            >
              PH值报警
            </Tag>
          </template>
        </vxe-column>
        <vxe-column field="levelStatus.value" title="液位状态">
          <template #default="{ row }">
            <Tag :color="row.levelStatus.value ? 'success' : 'error'">
              {{ row.levelStatus.value ? '高' : '低' }}
            </Tag>
          </template>
        </vxe-column>
      </vxe-table>

      <div class="section">
        <div class="quadrant-title">风机控制</div>
        <div class="fan-box">
          <div class="fan-control" v-for="(fan, index) in fans" :key="index">
            <h3>
              {{ fan.type === 'acid' ? '酸风机' : '铬风机' }}
            </h3>
            <div class="control-group">
              <Button
                class="ivu-btn"
                :type="fan.power.value ? 'success' : 'error'"
                @click="toggleFan(index, 'power')"
              >
                {{ fan.power.value ? '运行中' : '已停止' }}
              </Button>
              <RadioGroup
                type="button"
                v-model="fan.speed.value"
                @on-change="changeFanSpeed(index)"
              >
                <Radio label="high">高速</Radio>
                <Radio label="low">低速</Radio>
              </RadioGroup>
              <Button
                :type="fan.spray.value ? 'success' : 'error'"
                @click="toggleFan(index, 'spray')"
              >
                {{ fan.spray.value ? '喷淋开启' : '喷淋关闭' }}
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {
  Tsrv,
  T_srv,
  ifs,
  ts,
  vue,
  I_cmd,
  T_cmd,
  phTanks,
  fans,
  N_wasteGasTreatment
} from './config';

@T_srv.comp
export default class cWasteGasTreatment extends vue {
  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  /* 组件名 */
  private name: string = 'cWasteGasTreatment';

  private funName: string = 'cWasteGasTreament';

  private G_compName: string = this.name;

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  /* 指挥部 */
  private GT_command: I_cmd = new T_cmd();

  private isMask: boolean = false;

  public ecDetCodes: string[] = [];

  public phTanks: N_wasteGasTreatment.PhTank[] = phTanks();

  private fans: N_wasteGasTreatment.fan[] = fans();

  created() {
    // 如果父组件没有传参，那就产生一个
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    this.GT_command.init(this, this.GT_compBoxInfo);
    this.init();
  }

  mounted() {
    /* 向父组件发送实例 */
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    this.$emit('compBoxInfo', this.GT_compBoxInfo);
    this.GT_command.startTask();
    this.receiveEvent();
  }

  private receiveEvent() {
    this.$bus.$on(
      '__PLC_CONNSTATE__',
      (data: { connState: boolean; ecBoxName: string }) => {
        if (data.ecBoxName === 'mianyang') {
          if (data.connState) {
            if (!this.GT_command.isOpenTask) {
              this.GT_command.startTask();
            }
          } else {
            this.GT_command.stopTask();
          }
        }
      }
    );
  }

  private init() {
    this.ecDetCodes = [];
    this.phTanks.forEach(item => {
      Object.keys(item).forEach(key => {
        if (key !== 'name') {
          this.ecDetCodes.push(item[key].code);
        }
      });
    });

    this.fans.forEach(item => {
      Object.keys(item).forEach(key => {
        if (key !== 'type') {
          this.ecDetCodes.push(item[key].code);
        }
      });
    });

    Tsrv.readPlcData(this.ecDetCodes).then(res => {
      if (typeof res !== 'boolean') {
        this.updateData(res);
      }
    });
  }

  destroyed() {
    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);
    this.$bus.$off('__PLC_CONNSTATE__');

    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
  }

  beforeDestroy() {
    this.GT_command.stopTask();
  }

  public updateData(data: any) {
    this.phTanks.forEach(item => {
      Object.keys(item).forEach(key => {
        if (key !== 'name' && key !== '_XID') {
          if (item[key].conversionRate === undefined) {
            item[key].value = data[item[key].code].v;
          } else {
            item[key].value = data[item[key].code].v / item[key].conversionRate;
          }
        }
      });
    });

    this.fans.forEach(item => {
      Object.keys(item).forEach(key => {
        if (key !== 'type' && key !== '_XID') {
          if (key === 'speed') {
            item[key].value = data[item[key].code].v ? 'low' : 'high';
          } else {
            item[key].value = data[item[key].code].v;
          }
        }
      });
    });
  }

  // 失焦事件处理
  public handleBlur(row: any, field: string, param: string) {
    const rowData: N_wasteGasTreatment.setInfo = row[field];
    const newValue =
      row[field].conversionRate === undefined
        ? rowData.value
        : (rowData.value as number) * rowData.conversionRate;

    const d = [{ ecDetCode: row[field].code, value: newValue.toString() }];
    Tsrv.writePlcData(d).then(_ => {
      // 读取数据
      Tsrv.readPlcData([row[field].code]).then(res => {
        if (typeof res !== 'boolean') {
          this[param].forEach(item => {
            if (item.name === row.name) {
              if (row[field].conversionRate === undefined) {
                item[field].value = res[row[field].code].v;
              } else {
                item[field].value =
                  res[row[field].code].v / rowData.conversionRate;
              }
              // item[field].value = res[row[field].code].v;
            }
          });
        }
      });
    });
  }

  private handleSwitchChange(
    row: any,
    field: string,
    param: string,
    value: boolean
  ) {
    const valueStr =
      field === 'autoSwitch' ? value.toString() : (!value).toString();
    const d = [{ ecDetCode: row[field].code, value: valueStr }];
    Tsrv.writePlcData(d).then(_ => {
      // 读取数据
      Tsrv.readPlcData([row[field].code]).then(res => {
        if (typeof res !== 'boolean') {
          this[param].forEach(item => {
            if (item.name === row.name) {
              item[field].value = res[row[field].code].v;
            }
          });
        }
      });
    });
  }

  private toggleFan(index: number, type: 'power' | 'spray') {
    const fan = this.fans[index];
    const code = fan[type].code;
    const value = !fan[type].value;

    Tsrv.writePlcData([{ ecDetCode: code, value: value.toString() }]).then(
      _ => {
        // fan[type].value = value;
        Tsrv.readPlcData([code]).then(res => {
          if (typeof res !== 'boolean') {
            fan[type].value = res[code].v;
          }
        });
      }
    );
  }

  private changeFanSpeed(index: number) {
    const fan = this.fans[index];
    const value = fan.speed.value === 'high';

    Tsrv.writePlcData([
      {
        ecDetCode: fan.speed.code,
        value: value.toString()
      }
    ]).then(_ => {
      Tsrv.readPlcData([fan.speed.code]).then(res => {
        if (typeof res !== 'boolean') {
          fan.speed.value = res[fan.speed.code].v ? 'low' : 'high';
        }
      });
    });
  }
}
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
  display: flex;
  flex-direction: column;

  .quadrant-title {
    font-size: 16px;
    font-weight: bold;
    padding: 8px 12px;
    background: #f5f7fa;
    border: 1px solid #dcdfe6;
    border-radius: 4px 4px 0 0;
    margin-bottom: -1px;
  }
  .section {
    margin-top: 25px;
    background: white;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    .fan-control {
      margin-bottom: 15px;
      padding: 12px;
      background: #fafafa;
      border-radius: 4px;
    }

    .fan-box {
      width: 100%;
      height: 100%;
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 16px;

      h3 {
        padding-bottom: 15px;
        color: #17233d;
        font-size: 16px;
        font-weight: 500;
        display: flex;
        align-items: center;
        border-bottom: #dcdfe6 1px solid;

        &::before {
          content: '';
          display: inline-block;
          width: 4px;
          height: 16px;
          background: #2d8cf0;
          margin-right: 8px;
          border-radius: 2px;
        }
      }
      .control-group {
        display: flex;
        gap: 12px;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        height: 100%;

        .ivu-btn {
          min-width: 80px;
          transition: all 0.2s;

          &:hover {
            transform: translateY(-2px);
          }
        }

        .ivu-radio-group {
          background: #f8f8f8;
          padding: 4px;
          border-radius: 4px;
        }

        .btn-status {
          width: 100px;
          height: 30px;
          display: flex;
          justify-content: center;
          align-items: center;
          border: #e8e8e8 1px solid;
          border-radius: 5px;
          background-color: #fff;
          color: #515a6e;
        }
        .active {
          background-color: #2d8cf0;
          color: #fff;
        }
      }
    }

    h4 {
      margin: 10px 0;
      color: #515a6e;
      font-size: 14px;
    }
  }
}
</style>
